<template>
  <EcDialog v-model="dialogVisible" :auto-height="false" class="form-dialog footer-center" width="50%">
    <!-- 标题 -->
    <template #title>
      <div class="dialog-title">
        <SvgIcon :icon="dialogIconMap[dialogMode]"/>
        <span>{{ dialogTitle }}</span>
      </div>
    </template>

    <!-- 步骤限制 -->
    <el-steps :active="stepActive" align-center style="width: 100%">
      <el-step title="修改范围"/>
      <el-step title="修改内容"/>
      <el-step title="保存数据"/>
    </el-steps>

    <!-- 修改范围 -->
    <div v-if="stepActive == 1" class="step-range">
      <el-form ref="rangeFormRef" :model="rangeFormData" label-width="92px">
        <el-form-item label="商品分类：" prop="cate_ids">
          <el-cascader ref="cateCascaderRef"
                       v-model="rangeFormData.cate_ids"
                       :options="cateList"
                       :props="cascaderProps"
                       clearable
                       collapse-tags
                       filterable
                       placeholder="请选择分类"/>
        </el-form-item>
        <el-form-item label="归属店铺：" prop="shop_ids">
          <el-cascader ref="shopCascaderRef"
                       v-model="rangeFormData.shop_ids"
                       :options="shopList"
                       :props="cascaderProps"
                       clearable
                       collapse-tags
                       filterable
                       placeholder="请选择店铺"/>
        </el-form-item>
      </el-form>
    </div>

    <!-- 修改内容  -->
    <el-form v-if="stepActive == 2" ref="formRef" v-loading="dataLoading"
             :model="formData"
             :rules="formRules"
             label-width="92px">

      <el-tabs class="modify-tabs" tab-position="left">
        <el-tab-pane v-if="tabType == 2 || tabType == 3" label="商品审核">
          <el-form-item label="审核状态：" prop="audit_status">
            <el-radio-group v-model="formData.audit_status">
              <el-radio-button :value="1">通过</el-radio-button>
              <el-radio-button :value="0">拒绝</el-radio-button>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="审核原因：" prop="audit_reason">
            <el-input v-model="formData.audit_reason" :autosize="{ minRows: 2}" :maxlength="128" placeholder="请输入审核原因" type="textarea"/>
          </el-form-item>
        </el-tab-pane>

        <el-tab-pane v-if="tabType == 1 || tabType == 5" label="商品状态">
          <el-form-item label="商品状态：" prop="status">
            <el-radio-group v-model="formData.status">
              <el-radio-button :value="100">上架</el-radio-button>
              <el-radio-button :value="110">下架</el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-tab-pane>

        <el-tab-pane label="让利设置">
          <el-form-item label="补贴配置：" prop="subsidy_config_id">
            <el-select v-model="formData.subsidy_config_id" placeholder="请选择补贴配置" style="width: 60%" value="" @change="handleChangeSubsidyConfig">
              <el-option v-for="item in subsidyConfigList" :key="item.id" :label="item.name" :value="item.id">
                <span style="float: left">{{ item.name }}</span>
                <span v-if="item.mode" style="float: right;color: var(--el-text-color-secondary);font-size: 13px;">{{ item.mode == 2 ? '2.0' : item.mode == 1 ? '1.0' : '' }}</span>
              </el-option>
            </el-select>
          </el-form-item>

          <template v-if="!formData.subsidy_config_id">
            <el-form-item label="补贴比例：" prop="subsidy_ratio">
              <el-input-number v-model="formData.subsidy_ratio" :max="1" :min="0" :precision="3" :step="0.1" controls-position="right"/>
              <span v-if="formData.subsidy_ratio != undefined" class="tip">{{ toPercent(formData.subsidy_ratio) }}</span>
            </el-form-item>

            <el-form-item label="让利比例：" prop="rebate_ratio">
              <el-input-number v-model="formData.rebate_ratio" :max="0.9" :min="0" :precision="3" :step="0.1" controls-position="right"/>
              <span v-if="formData.rebate_ratio != undefined" class="tip">{{ toPercent(formData.rebate_ratio) }}</span>
            </el-form-item>

            <el-form-item label="推广奖金：" prop="promotion_ratio">
              <el-input-number v-model="formData.promotion_ratio" :max="0.2" :min="0" :precision="3" :step="0.1" controls-position="right"/>
              <span v-if="formData.promotion_ratio != undefined" class="tip">{{ toPercent(formData.promotion_ratio) }}</span>
            </el-form-item>

            <el-form-item label="联盟服务费：" prop="service_ratio">
              <el-input-number v-model="formData.service_fee_ratio" :max="0.2" :min="0" :precision="3" :step="0.1" controls-position="right"/>
              <span v-if="formData.service_fee_ratio != undefined" class="tip">{{ toPercent(formData.service_fee_ratio) }}</span>
            </el-form-item>
          </template>
        </el-tab-pane>

        <el-tab-pane label="商品标签">
          <el-form-item label="商品标签：" prop="markFlag">
            <el-checkbox-group v-model="markFlagList" @change="handleChangeMarkFlag">
              <el-checkbox v-for="item in markFlagOptions" :key="item.value" :value="item.value">
                {{ item.label }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-tab-pane>

        <el-tab-pane label="限购数量">
          <el-form-item label="限购数量：" prop="buy_limit">
            <el-input-number v-model="formData.buy_limit" :min="0" :precision="0" :step="1" controls-position="right"/>
            <span class="tip">0 = 无限制</span>
          </el-form-item>
        </el-tab-pane>

        <el-tab-pane label="归属店铺">
          <el-form-item label="归属店铺：" prop="shop_id">
            <el-select v-model="formData.shop_id" placeholder="请选择归属店铺" value="">
              <el-option v-for="item in shopList" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-tab-pane>
      </el-tabs>
    </el-form>

    <!-- 底部操作区域 -->
    <template #footer>
      <span class="dialog-footer">
        <el-button :loading="dataLoading" style="width: 15rem" type="primary" @click="handleStep">确 认</el-button>
      </span>
    </template>
  </EcDialog>
</template>

<script lang="ts" setup>
import { computed, reactive, ref } from 'vue';
import { ElLoading, ElMessage, ElNotification, FormInstance, FormRules } from 'element-plus';
import { EcDialog } from '@/components/dialog';
import { SvgIcon } from '@/components/icon';
import useDialog from '@/hooks/use-dialog.ts';
import { goodsBatchUpdate, goodsCategoryTreeList, shopSimpleList } from '@/api/api-shop.ts';
import { goodsMarkFlagOptions } from '@/utils/global-dict.ts';
import { BaseCategory, BaseShopData } from '@/api/common.ts';
import { toPercent } from '@/utils';
import { SubsidyConfig, subsidyConfigTypeList } from '@/api/api-subsidy.ts';

defineOptions({name: 'goods-batch-modify'})

const formRef = ref<FormInstance>();
const formLoading = ref(false); // 表单是否加载中
const {dialogVisible, dialogTitle, dialogMode, dialogModeMap, dialogIconMap} = useDialog(false);

export type GoodsBatchModify = {
  status?: number;
  buy_limit?: number;
  mark_flag?: number;
  audit_status?: number;
  audit_reason?: string;
  subsidy_config_id?: number;
  rebate_ratio?: number;
  subsidy_ratio?: number;
  promotion_ratio?: number;
  service_fee_ratio?: number;
  shop_id?: number;
};

export type RangeData = {
  ids?: number[];
  cate_ids?: number[];
  shop_ids?: number[];
};

/** 默认表单数据 */
const defaultForm: GoodsBatchModify = <GoodsBatchModify>{};
const stepActive = ref(1);

// 表单数据
const formData = ref({...defaultForm});
// 表单验证规则
const formRules = reactive<FormRules>({});

const rangeFormRef = ref<FormInstance>();
const defRangeForm: RangeData = <RangeData>{};
const rangeFormData = ref({...defRangeForm});

/** 判断数据是否处于加载中 */
const dataLoading = computed(() => {
  return formLoading.value;
})

const tabType = ref(0);

/** 打开弹窗 */
const open = async (ids?: number[], type = 0) => {
  dialogMode.value = 2;
  dialogTitle.value = '商品批量操作';
  dialogVisible.value = true;
  // 重置表单
  handleFormReset();
  // 导航栏类型
  tabType.value = type;

  // 加载补贴配置
  await initSubsidyConfigs();

  if (ids && ids.length > 0) {
    stepActive.value = 2;
    rangeFormData.value.ids = ids;
    // 加载商家数据
    await initShopData();
  } else {
    // 加载分类信息
    await initCateList();
    // 加载商家数据
    await initShopData();
  }
}
// 提供 open 方法，用于打开弹窗
defineExpose({open});

/** 商品标签信息 */
const markFlagUpdate = ref(false);
const markFlagList = ref<number[]>([]);
const markFlagOptions = reactive(goodsMarkFlagOptions);
const handleMarkFlagUpdate = () => {
  let markFlag = 0
  markFlagList.value.forEach(it => markFlag |= it);
  formData.value.mark_flag = markFlag > 0 ? markFlag : 0;
  return formData.value.mark_flag;
};

const handleChangeMarkFlag = () => {
  markFlagUpdate.value = true;
  handleMarkFlagUpdate();
};

/** 加载顶级分类信息 */
const cateList = ref<BaseCategory[]>([]);
const cateListLoading = ref(false);
const cascaderProps = {
  value: 'id',
  label: 'name',
  multiple: true,
}
const initCateList = async () => {
  cateListLoading.value = true
  try {
    const {data} = await goodsCategoryTreeList();
    cateList.value = data
  } finally {
    cateListLoading.value = false
  }
};

/** 初始化商家列表 */
const shopList = ref<BaseShopData[]>([]);
const initShopData = async () => {
  shopList.value = [];
  const {data} = await shopSimpleList({type: 10});
  shopList.value = data;
};

/** 加载补贴配置 */
const subsidyConfigList = ref<SubsidyConfig[]>([]);
const initSubsidyConfigs = async () => {
  subsidyConfigList.value = [];
  const {data} = await subsidyConfigTypeList(10);
  subsidyConfigList.value = data || []
};

/** 处理下一步操作 */
const cateCascaderRef = ref();
const shopCascaderRef = ref();
const handleStep = () => {
  // 如果当前步骤为第1步 条件
  if (stepActive.value == 1) {
    // 条件校检
    let data = rangeFormData.value;
    let cateIds = cateCascaderRef.value?.getCheckedNodes().map((item: any) => item.value);
    let shopIds = shopCascaderRef.value?.getCheckedNodes().map((item: any) => item.value);
    if ((!data.ids || data.ids.length == 0) && (cateIds.length == 0) && (shopIds.length == 0)) {
      ElMessage({type: 'error', message: '请完善修改范围',});
      return;
    }
    rangeFormData.value.cate_ids = cateIds;
    rangeFormData.value.shop_ids = shopIds;
    stepActive.value = 2;
  } else if (stepActive.value == 2) {
    // 修改内容
    let updates = [];
    // 状态修改
    if (formData.value.status) {
      // @ts-ignore
      updates.push({type: 1, status: formData.value.status})
    }
    // 审核状态修改
    if (formData.value.audit_status != undefined) {
      // @ts-ignore
      updates.push({type: 2, audit_status: formData.value.audit_status, audit_reason: formData.value.audit_reason})
    }

    // 让例比例
    if (formData.value.subsidy_config_id != undefined && formData.value.subsidy_config_id > 0) {
      // @ts-ignore
      updates.push({type: 3, subsidy_config_id: formData.value.subsidy_config_id},)
    } else if (formData.value.rebate_ratio != undefined && formData.value.subsidy_ratio != undefined) {
      // @ts-ignore
      updates.push({type: 3, rebate_ratio: formData.value.rebate_ratio, subsidy_ratio: formData.value.subsidy_ratio, promotion_ratio: formData.value.promotion_ratio, service_fee_ratio: formData.value.service_fee_ratio,},)
    }

    // 商品标签修改
    if (markFlagUpdate.value) {
      // @ts-ignore
      updates.push({type: 10, mark_flag: formData.value.mark_flag})
    }
    // 限购数量
    if (formData.value.buy_limit != undefined) {
      // @ts-ignore
      updates.push({type: 11, buy_Limit: formData.value.buy_limit})
    }
    // 归属店铺
    let shop_id = formData.value.shop_id;
    if (shop_id != undefined && shop_id > 0) {
      // @ts-ignore
      updates.push({type: 12, shop_id: shop_id})
    }
    // 校检修改的条目
    if (updates.length == 0) {
      ElMessage({type: 'error', message: '请选择修改的内容',});
      return;
    }
    // 封装参数
    let params = {
      ids: rangeFormData.value.ids,
      cate_ids: rangeFormData.value.cate_ids,
      shop_ids: rangeFormData.value.shop_ids,
      updates: updates
    };
    // 提交修改
    onSubmitForm(params);
  }
};

/** 表单提交 */
const emit = defineEmits(['refresh']);
const onSubmitForm = async (params: any) => {
  const loading = ElLoading.service({
    lock: true,
    text: '正在提交中...',
    background: 'rgba(0, 0, 0, 0.2)'
  })
  // 提交数据
  goodsBatchUpdate(params).then(response => {
    // 提示信息
    ElNotification({title: '成功', message: '操作完成', type: 'success', duration: 2000})
    // 发送操作成功的事件
    emit('refresh')
    // 隐藏窗口
    dialogVisible.value = false
  }).finally(() => loading.close())
};

/** 重置表单 */
const handleFormReset = () => {
  stepActive.value = 1;
  // 重置表单数据
  formData.value = {...defaultForm};
  // 重置界面表单数据
  formRef.value?.resetFields();

  // 范围条件
  rangeFormData.value = {...defRangeForm};
  rangeFormRef.value?.resetFields();

  // 商品标签
  markFlagList.value = [];
  markFlagUpdate.value = false;
};

/** 补贴配置选择改变 */
const handleChangeSubsidyConfig = (val: any) => {
  let item = subsidyConfigList.value.find(item => item.id == val);
  if (item) {
    formData.value.rebate_ratio = item.rebate_ratio;
    formData.value.subsidy_ratio = item.subsidy_ratio;
    formData.value.promotion_ratio = item.promotion_ratio;
    formData.value.service_fee_ratio = item.service_fee_ratio;
  } else {
    formData.value.rebate_ratio = 0.0;
    formData.value.subsidy_ratio = 0.0;
    formData.value.promotion_ratio = 0.0;
    formData.value.service_fee_ratio = 0.0;
  }
};
</script>

<style lang="scss" scoped>
.form-dialog {
  .el-select {
    max-width: 13rem;
  }

  .el-input-number {
    max-width: 10rem;
  }
}

.modify-tabs {
  padding: 13px;
  height: 363px;

  :deep() {
    .el-tabs__content {
      padding: 13px;
      height: 100%;
    }
  }
}

.step-range {
  width: 70%;
  height: 100%;
  margin: auto;
  padding-top: 60px;
}
</style>
